<script setup>
import {  ref } from 'vue'
import { ElForm, ElFormItem, ElInput, 
    ElButton, ElCard, ElRow, ElCol, 
    ElMessage, ElRadio, ElRadioGroup
    } from 'element-plus'

import { useRouter } from 'vue-router';
import { userLoginService, getUserInfoService } from '@/api/user.js'
import { generateCaptcha, refreshCaptcha } from '@/utils/captcha.js'
// 引入store
import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo.js'

// 路由
const router = useRouter();

// 表单数据
const formData = ref({
  username: '',
  password: '',
  captcha: '',
  role: 'user' // 添加用户类型，默认为普通用户
});



// 用户信息
// const userData = ref({
//   id: '',
//   username: '',
//   password: '',
//   phone: '',
//   email: '',
//   student_id: '',// 学号
//   is_verified: false,// 是否已认证
//   avatar: '',
//   nickname: '',
//   bio: '',
//   role: '',
//   status: '',
//   last_login_time: '',
//   create_at: '',
//   update_at: ''
// });

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error('用户名长度不能少于2位'));
        } 
        else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error('密码长度不能少于5位'));
        } else if (!/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$/.test(value)) {
          callback(new Error('密码必须包含字母和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur'},
    { 
      validator: (rule, value, callback) => {
        if (value.length !== 4) {
          callback(new Error('验证码长度必须为4位'));
        } else if (value.toUpperCase() !== currentCaptcha.value.code) {
          callback(new Error('验证码不正确'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 表单引用
const formRef = ref();

// 将token和用户信息存入pinia
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

// 图形验证码相关
const currentCaptcha = ref(generateCaptcha());// 生成验证码数据
const captchaUrl = ref(currentCaptcha.value.imageUrl);// 生成验证码图片

// 刷新验证码
const refreshCaptchaHandler = () => {
  refreshCaptcha((data) => {
    currentCaptcha.value = data;
    captchaUrl.value = data.imageUrl;
  })
};

// 表单提交
// const Login = async () => {
//   try {
//     const Params = {  username: formData.value.username, 
//                     password: formData.value.password
//                   }
//     const res = await userLoginService(Params);
    
//     // 获取用户信息
//     const userInfo = await getUserInfoService();
    
//     // 检查用户角色是否匹配
//     if(userInfo.data.role != formData.value.role ){
//       ElMessage.error('登录失败: 用户角色不匹配');
//       return;
//     }

//     // 将token保存到pinia中（会自动持久化到sessionStorage）
//     tokenStore.setToken(res.data);

//     // 将用户信息保存到pinia中（会自动持久化到sessionStorage）
//     userInfoStore.setInfo(userInfo.data);

//     // 添加标签页ID相关的信息存储
//     let tabId = sessionStorage.getItem('tabId');
//     if (!tabId) {
//       // 如果没有tabId，则生成一个新的
//       tabId = 'tab-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
//       sessionStorage.setItem('tabId', tabId);
//     }
    
//     // 将用户信息和token存储到localStorage中，以tabId为key
//     localStorage.setItem(`token-${tabId}`, JSON.stringify({ 
//       token: res.data,
//       userInfo: userInfo.data,
//       timestamp: new Date().getTime()
//     }));

//     ElMessage.success('登录成功');
//     // 根据后端返回的用户类型决定跳转路径
//     if (userInfo.data.role === 'admin') {
//       router.push('/admin');
//     } else {
//       router.push('/');
//     }
//   } catch (error) {
//     const errorMessage = error.response?.data?.message || error.message || '登录失败';
//     ElMessage.error('登录失败: ' + errorMessage);
//   }
// };
// 表单提交
const Login = async () => {
    // 先进行表单验证
  try {
    await formRef.value.validate();
  } catch  {
    // 表单验证失败，不进行跳转，直接返回
    return;
  }
    
  // 单独检查验证码是否正确（不区分大小写）
  if (formData.value.captcha.toUpperCase() !== currentCaptcha.value.code) {
    ElMessage.error('验证码不正确');
    return;
  }
  try {
    const Params = {  username: formData.value.username, 
                    password: formData.value.password
                  }
    const res = await userLoginService(Params);
    
    // 将token保存到pinia中，同时保存到localStorage
    tokenStore.setToken(res.data);
    localStorage.setItem('token', res.data);
    console.log("token:"+res.data)

    // 获取用户信息
    const userInfo =await getUserInfoService(tokenStore.token)
    console.log(userInfo.data)
    
    // 将用户信息保存到pinia中，同时保存到localStorage
    userInfoStore.setInfo(userInfo.data);
    localStorage.setItem('userInfo', JSON.stringify(userInfo.data));
    console.log("userinfo:"+userInfo.data)

    if(userInfo.data.role != formData.value.role ){
      tokenStore.removeToken()
      userInfoStore.removeInfo()
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.error('登录失败: 用户角色不匹配');
      return;
    }

    ElMessage.success('登录成功');
    // 根据后端返回的用户类型决定跳转路径
    if (userInfo.data.role === 'admin') {
      router.push('/admin');
    } else {
      router.push('/');
    }
  } catch (error) {
    const errorMessage = error.response?.data?.message || error.message || '登录失败';
    ElMessage.error('登录失败: ' + errorMessage);
  }
};
</script>

<template>
  <el-row class="login-page">
    <!-- 左侧背景图片 -->
    <el-col :span="12" class="bg"></el-col>
    
    <!-- 右侧表单区域 -->
    <el-col :span="12" class="form-col">
      <div class="form-container">
        <div class="register-header">
          <h1 class="platform-name">
            <span class="app-name">校园信息平台</span>
          </h1>
          <p class="platform-desc">登录账号</p>
        </div>
        
        <el-card class="register-card">
          <h2 class="register-title">登录账号</h2>
          
          <el-form 
            ref="formRef"
            :model="formData" 
            :rules="rules" 
            label-width="80px" 
            class="register-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            
            <el-form-item label="验证码" prop="captcha">
              <div class="captcha-container">
                <el-input 
                  v-model="formData.captcha" 
                  placeholder="请输入验证码" 
                  class="captcha-input"
                  maxlength="4"
                />
                <img 
                  :src="captchaUrl" 
                  class="captcha-image" 
                  @click="refreshCaptchaHandler"
                  alt="验证码"
                />
              </div>
            </el-form-item>
            
            <el-form-item label="用户类型" prop="userType">
              <el-radio-group v-model="formData.role">
                <el-radio label="user">用户</el-radio>
                <el-radio label="admin">管理员</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="Login" class="register-btn">登录</el-button>
            </el-form-item>
          </el-form>
          
          <div class="login-link">
            <a href="/register">还没有账号？立即注册</a>
          </div>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  margin: 0 !important;
}

.bg {
  background: url("@/assets/images/login.jpg") no-repeat center;
  background-size: cover;
  border-radius: 0 20px 20px 0;
  height: 100vh;
  background-color: #f5f5f5; /* 添加背景色以防图片加载失败 */
}

.form-col {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 0;
}

.form-container {
  width: 100%;
  max-width: 450px;
  padding: 0 20px;
}

.register-header {
  margin-bottom: 30px;
  text-align: center;
}

.platform-name {
  font-size: 28px;
  margin-bottom: 10px;
  color: #333;
}

.app-name {
  color: #409eff;
  font-weight: bold;
}

.platform-desc {
  font-size: 16px;
  color: #666;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.register-card {
  padding: 30px;
  border: none;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
}

.register-title {
  text-align: center;
  margin-bottom: 25px;
  font-size: 22px;
  color: #333;
  font-weight: 600;
}

.register-form {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #555;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 12px 15px;
  transition: border-color 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

:deep(.el-radio__label) {
  color: #666;
}

.register-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, #409eff, #1a73e8);
  border: none;
  transition: all 0.3s ease;
  font-weight: 500;
  letter-spacing: 1px;
}

.register-btn:hover {
  background: linear-gradient(90deg, #1a73e8, #409eff);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transform: translateY(-2px);
}

.login-link {
  text-align: center;
  margin-top: 20px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
}

.login-link a:hover {
  text-decoration: underline;
  color: #1a73e8;
}

/* 头像相关样式 */

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  object-fit: cover;
}

/* 响应式设计 */


@media (max-width: 768px) {
  .login-page {
    flex-direction: column;
  }
  
  .bg {
    height: 200px;
    border-radius: 0;
    background-size: 120px auto, cover;
  }
  
  .form-col {
    height: auto;
    padding: 20px;
  }
  
  .form-container {
    padding: 0;
  }
  
  .register-card {
    padding: 20px;
  }
}

@media (max-width: 576px) {
  .register-header {
    margin-top: 20px;
  }
  
  .platform-name {
    font-size: 24px;
  }
  
  .register-card {
    padding: 15px;
  }
  
  .register-title {
    font-size: 20px;
  }
}
</style>
